package com.oa.admin.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.joneying.common.web.response.Resp;
import com.oa.admin.service.ISysUserTokenService;
import com.oa.core.utils.MD5Util;
import com.oa.system.entity.SysUserToken;
import com.oa.system.entity.User;
import com.oa.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ISysUserTokenService userTokenService;

    @PostMapping("/submit")
    @ResponseBody
    public Object loginSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = MD5Util.md5Password(request.getParameter("password"));

        Wrapper wrapper = new EntityWrapper();
        wrapper.where("username = {0} and password = {1}", username, password);
        User user = userService.selectOne(wrapper);

        if(user != null){
            SysUserToken userToken = userTokenService.createToken(user.getId());
            userToken.setUserId(null);
            return new Resp<>().success(userToken);
        }
        return new Resp<>().failure("账号或密码错误");
    }

    @GetMapping("/test")
    @ResponseBody
    public Object test(HttpServletRequest request){
        return userTokenService.queryByToken(request.getParameter("token"));
    }
}
